package com.jeesite.modules.fl.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.modules.fl.utils.FlConstants;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.UserUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.fl.entity.Enterprise;
import com.jeesite.modules.fl.entity.Leaguer;
import com.jeesite.modules.fl.service.EnterpriseService;
import com.jeesite.modules.fl.service.LeaguerService;

@Controller
@RequestMapping(value = "${adminPath}/fl/leaguer")
public class LeaguerController extends BaseController{
	
	@Autowired
	private LeaguerService leaguerService;
	@Autowired
	private EnterpriseService enterpriseService;
	@Autowired
	private UserService userService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Leaguer get(String id, boolean isNewRecord) {
		return leaguerService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("fl:leaguer:view")
	@RequestMapping(value = {"list", ""})
	public String list(Leaguer leaguer, HttpServletRequest request, HttpServletResponse response, Model model) {
		model.addAttribute("leaguer", leaguer);
		Enterprise entity = new Enterprise();
        entity.setStatus("0");
        List<Enterprise> enterpriseList = enterpriseService.findList(entity);
        model.addAttribute("enterpriseList", enterpriseList);
		return "modules/fl/leaguerList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("fl:leaguer:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Leaguer> listData(Leaguer leaguer, HttpServletRequest request, HttpServletResponse response) {
		Page<Leaguer> page = leaguerService.findPage(new Page<Leaguer>(request, response), leaguer);
		return page;
	}
	
	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("fl:leaguer:view")
	@RequestMapping(value = "form")
	public String form(Leaguer leaguer, Model model) {
		model.addAttribute("leaguer", leaguer);
		Enterprise entity = new Enterprise();
        entity.setStatus("0");
        List<Enterprise> enterpriseList = enterpriseService.findList(entity);
        model.addAttribute("enterpriseList", enterpriseList);
		return "modules/fl/leaguerForm";
	}
	
	/**
	 * 验证名称是否有效
	 * @param oldLeaguerCellphone
	 * @param cellphone
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("fl:leaguer:edit")
	@RequestMapping(value = "checkLeaguerCellphone")
	public String checkLeaguerCellphone(String oldLeaguerCellphone, String cellphone) {
		if (cellphone !=null && cellphone.equals(oldLeaguerCellphone)) {
			return "true";
		} else if (cellphone !=null && leaguerService.getByCellphone(cellphone) == null) {
			return "true";
		}
		return "false";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("fl:leaguer:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Leaguer leaguer, HttpServletRequest request) {
		if(leaguer.getEnterprise() != null && leaguer.getEnterprise().getId() != null){
			leaguer.setIsEnterprise(true);
		}else{
			leaguer.setIsEnterprise(false);
		}
		if(leaguer.getIsNewRecord()){
			leaguer.setRegisterDate(new Date());
			if(leaguer.getPassword() == null ||leaguer.getPassword().isEmpty()){
				String cellphone = leaguer.getCellphone();	
				String password = cellphone.substring(cellphone.length()-6);
				leaguer.setPassword(password);
			}
		}
		if (leaguer.getOpenId() == null) {
			Session session = UserUtils.getSession();
			Object openId = session.getAttribute(FlConstants.SESS_OPEN_ID);
			if (openId != null) {
				logger.debug("set open id {} for leaguer {}", openId.toString(), leaguer.getCellphone());
				leaguer.setOpenId(openId.toString());
			}
		}
		leaguerService.save(leaguer);
		return renderResult(Global.TRUE, text("保存数据成功！"));
	}
	
	/**
	 * 停用数据
	 */
	@RequiresPermissions("fl:leaguer:edit")
	@RequestMapping(value = "disable")
	@ResponseBody
	public String disable(Leaguer leaguer) {
		leaguer.setStatus(Leaguer.STATUS_DISABLE);
		leaguerService.updateStatus(leaguer);
		return renderResult(Global.TRUE, text("停用数据成功"));
	}
	
	/**
	 * 修改密码
	 */
	@RequiresPermissions("fl:leaguer:edit")
	@RequestMapping(value = "changePassword")
	@ResponseBody
	public String changePassword(Leaguer leaguer, String password) {
		if(password == null || password.isEmpty()){
			return renderResult(Global.FALSE, text("新密码不能为空！"));
		}
		User user = new User();
        user.setLoginCode(leaguer.getCellphone());
        user = userService.getByLoginCode(user);
        userService.updatePassword(user.getId(), password);
        leaguer.setPassword(password);
        leaguerService.save(leaguer);
		return renderResult(Global.TRUE, text("修改密码成功！"));
	}
	
	/**
	 * 启用数据
	 */
	@RequiresPermissions("fl:leaguer:edit")
	@RequestMapping(value = "enable")
	@ResponseBody
	public String enable(Leaguer leaguer) {
		leaguer.setStatus(Leaguer.STATUS_NORMAL);
		leaguerService.updateStatus(leaguer);
		return renderResult(Global.TRUE, text("启用数据成功"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("fl:leaguer:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Leaguer leaguer) {
		leaguerService.delete(leaguer);
		return renderResult(Global.TRUE, text("删除数据成功！"));
	}
	
	@RequestMapping(value = "import/leaguerTemplate")
	public void importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("会员数据", Leaguer.class);
		try {
			String fileName = "会员数据导入模板.xlsx";
			List<Leaguer> list = new ArrayList<Leaguer>();
			ee.setDataList(list).write(response, fileName).close();
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
	}
	
	@RequestMapping(value = "export", method=RequestMethod.POST)
    public void exportFile(Leaguer leaguer, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		ExcelExport ee = new ExcelExport("会员数据", Leaguer.class);
		try {
            String fileName = "会员数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; 	
            List<Leaguer> list = leaguerService.findList(leaguer);
    		ee.setDataList(list).write(response, fileName);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出会员失败！失败信息："+e.getMessage());
		} finally{
			ee.close();
		}
    }
    
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importData(MultipartFile file, String updateSupport)
    {
        String message = "";
        boolean isUpdateSupport = "1".equals(updateSupport);
        try{
	        message = leaguerService.importData(file, Boolean.valueOf(isUpdateSupport));
	        return renderResult("true", (new StringBuilder()).append("posfull:").append(message).toString());
        }catch(Exception ex){
        	return renderResult("false", (new StringBuilder()).append("posfull:").append(ex.getMessage()).toString());
        }
    }

}
